#include "svghelper.h"
#include <QBuffer>
#include <QFileInfo>
#include <QDebug>

SvgHelper::SvgHelper(const QString &filename)
{
    setFileName(filename);
}

bool SvgHelper::isSvgFile(const QString &filename)
{
    auto suffix = QFileInfo(filename).suffix();
    return suffix == "xml" || suffix == "svg";
}

QByteArray SvgHelper::filled(const QString &filename, const QColor &color)
{
    return SvgHelper(filename).filled(color);
}

QByteArray SvgHelper::opacityOnly(const QString &filename, float alpha)
{
    return SvgHelper(filename).opacityOnly(alpha);
}

QByteArray SvgHelper::cloned(const QString &filename)
{
    return SvgHelper(filename).cloned();
}

QByteArray SvgHelper::filled(const QColor &color) const
{
    auto paths = doc.elementsByTagName("path");
    for (int i = 0; i < paths.size(); ++i) {
        auto pathNode = paths.item(i);
        pathNode.toElement().setAttribute("fill", color.name(QColor::HexRgb));
        // set "fill-opacity" attribute
        pathNode.toElement().setAttribute("fill-opacity", color.alphaF());
    }
    QBuffer buffer;
    buffer.open(QIODevice::WriteOnly);
    QTextStream stream(&buffer);
    doc.save(stream, 0);
    // now buffer get new data
    return buffer.data();
}

QByteArray SvgHelper::opacityOnly(float alpha) const
{
    auto paths = doc.elementsByTagName("path");
    for (int i = 0; i < paths.size(); ++i) {
        auto pathNode = paths.item(i);
        // set "fill-opacity" attribute
        pathNode.toElement().setAttribute("fill-opacity", alpha);
    }
    QBuffer buffer;
    buffer.open(QIODevice::WriteOnly);
    QTextStream stream(&buffer);
    doc.save(stream, 0);
    // now buffer get new data
    return buffer.data();
}

QByteArray SvgHelper::cloned() const
{
    QBuffer buffer;
    buffer.open(QIODevice::WriteOnly);
    QTextStream stream(&buffer);
    doc.save(stream, 0);
    // now buffer get new data
    return buffer.data();
}

SvgHelper &SvgHelper::setFileName(const QString &fileName)
{
    QFile file(fileName);
    file.open(QIODevice::ReadOnly);
    QString errMsg;
    int errRow, errCol;
    doc.setContent(file.readAll(), &errMsg, &errRow, &errCol);
    file.close();
    if (!errMsg.isEmpty()) {
        qDebug() << QString("Error causes while reading file in (%1,%2). Error message: %3")
                        .arg(errRow)
                        .arg(errCol)
                        .arg(errMsg);
    }
    return *this;
}
